package io.renren.modules.sale.controller;

import io.renren.common.utils.R;
import io.renren.modules.sale.service.ISkuInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/sku")
@Api("SKU相关接口")
public class SkuInfoController {

    @Autowired
    ISkuInfo iSkuInfo;

    @GetMapping("getSkuInfo")
    @ResponseBody
    @ApiOperation("获取sku信息")
    public R getSkuInfo(){
        return R.ok().put("sku", iSkuInfo.getSkuInfo());
    }

    @RequestMapping(value="/upload/{time}",method={RequestMethod.POST})
    @ResponseBody
    public R upload(@PathVariable("time") String time, @RequestParam("file") MultipartFile file, HttpServlet request) throws IOException {
        String fileName=file.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf(".")+1); // 后缀: "xls"
        String path=request.getServletContext().getRealPath(File.separator+"myFile");
        String date=String.valueOf(new Date().getTime());
        if(!new File(path).exists()){
            new File(path).mkdir();
        }
        File file2=new File(path+File.separator+date+"_"+fileName);
        file.transferTo(file2);
        return R.ok();
    }


    @PostMapping("uploadExcel")
    public R uploadExcelFile(HttpServletRequest request, MultipartFile file){
        try {
            //生成uuid
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //得到上传时的文件名
            String filename=file.getOriginalFilename();
            //上传目录地址
            //1.1保存到项目指定目录
            String uploadDir="F:\\upload";
            //1.2 上传到相对路径 request.getSession().getServletContext().getRealPath("/")+"upload/";
            //1.2 此路径为tomcat下，可以输出看一看

            //如果目录不存在，自动创建文件夹
            File dir=new File(uploadDir);
            if(!dir.exists()){
                dir.mkdir();
            }

            //保存文件对象 加上uuid是为了防止文件重名
            File serverFile=new File(uploadDir+"\\"+uuid+filename);
            file.transferTo(serverFile);
        } catch (Exception e) {
            //打印错误堆栈信息
            e.printStackTrace();
            return R.ok("上传失败");
        }

        return R.ok("上传成功");
    }
}
